﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Applications.Core.Client;
using System.Data;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using Pcm.Retail.Client;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Engine.UI.Forms;

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Contact : FormClientTask
    {
        /// <summary>
        /// Saves the Contact record
        /// </summary>
        /// <returns>Returns true for successful save else false</returns>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        public override bool SaveRecord()
        {
            bool saveRecord = false;
            try
            {
                //DS:27032013 - Set the fields which was earlier getting set on form formula.
                SetMobilePhoneFax();

                if (this.RecordId == null)
                {
                    saveRecord = this.AddRecord();
                }
                else
                {
                    if (ContactDupCheck())
                        return false;

                    //On change of field RE_Status, create a new Membership History record.
                    if (!string.Equals(TypeConvert.ToString(this.PrimaryDataRow["RE_Status"]), TypeConvert.ToString(this.PrimaryDataRow["RE_Status", DataRowVersion.Original])))
                    {
                        //Create a new row in the RE_Membership_History table.
                        DataRow reMembershipHistoryRow = this.DataSet.Tables["RE_Membership_History_Contact_"].NewRow();
                        reMembershipHistoryRow["Contact_Id"] = TypeConvert.ToDBValue(this.RecordId);
                        reMembershipHistoryRow["Activity"] = "Status Changed";
                        reMembershipHistoryRow["Activity_Description"] = "Status changed from '" + TypeConvert.ToString(this.PrimaryDataRow["RE_Status", DataRowVersion.Original])
                            + "' to '" + TypeConvert.ToString(this.PrimaryDataRow["RE_Status"]) + "'";
                        reMembershipHistoryRow["Activity_Date"] = DateTime.Now;

                        this.DataSet.Tables["RE_Membership_History_Contact_"].Rows.Add(reMembershipHistoryRow);
                    }                    
                    
                    //If the Membership ID field is changed from its initial value to a different one, Create a new row in the RE_Membership_History table.
                    if (!string.Equals(this.PrimaryDataRow["RE_Membership_ID"].ToString(), this.PrimaryDataRow["RE_Membership_ID", DataRowVersion.Original].ToString()))
                    {
                        //Create a new row in the RE_Membership_History table.
                        DataRow reMembershipHistoryRow = this.DataSet.Tables["RE_Membership_History_Contact_"].NewRow();
                        reMembershipHistoryRow["Contact_Id"] = TypeConvert.ToDBValue(this.RecordId);
                        reMembershipHistoryRow["Activity"] = "Card Replaced";
                        reMembershipHistoryRow["Activity_Description"] = "Membership ID Changed";
                        reMembershipHistoryRow["Activity_Date"] = DateTime.Now;

                        this.DataSet.Tables["RE_Membership_History_Contact_"].Rows.Add(reMembershipHistoryRow); 
                    }
                    
                    saveRecord = base.SaveRecord();
                    base.LoadRecord();
                }
            }
            catch (Exception exc)
            {
                return Globals.HandleException(exc, true);
            }
            return saveRecord;
        }

        /// <summary>
        /// Set the Phone, Mobile and Fax fields from the splitted up fields.   
        /// </summary>
        private void SetMobilePhoneFax()
        {
            //NN 24 May 2013:Added code to check for NULL values
            //If all the 3 values are NULL then setting the Main field as NULL
            if (TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Country_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Area_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Number"]) != string.Empty)
            {
                this.PrimaryDataRow["Mobile"] = '+' + TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Country_Code"]) +
                                        TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Area_Code"]) + TypeConvert.ToString(this.PrimaryDataRow["RE_Mobile_Number"]);
            }
            else
                this.PrimaryDataRow["Mobile"] = DBNull.Value;
            //NN 24 May 2013:Added code to check for NULL values
            //If all the 3 values are NULL then setting the Main field as NULL
            if (TypeConvert.ToString(this.PrimaryDataRow["RE_Phone_Country_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Phone_Area_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Phone_Number"]) != string.Empty)
            {
                this.PrimaryDataRow["Phone"] = '+' + TypeConvert.ToString(this.PrimaryDataRow["RE_Phone_Country_Code"]) +
                                        TypeConvert.ToString(this.PrimaryDataRow["RE_Phone_Area_Code"]) + TypeConvert.ToString(this.PrimaryDataRow["RE_Phone_Number"]);
            }
            else
                this.PrimaryDataRow["Phone"] = DBNull.Value;
            //NN 24 May 2013:Added code to check for NULL values
            //If all the 3 values are NULL then setting the Main field as NULL
            if (TypeConvert.ToString(this.PrimaryDataRow["RE_Fax_Country_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Fax_Area_Code"]) != string.Empty ||
                TypeConvert.ToString(this.PrimaryDataRow["RE_Fax_Number"]) != string.Empty)
            {
                this.PrimaryDataRow["Fax"] = '+' + TypeConvert.ToString(this.PrimaryDataRow["RE_Fax_Country_Code"]) +
                                        TypeConvert.ToString(this.PrimaryDataRow["RE_Fax_Area_Code"]) + TypeConvert.ToString(this.PrimaryDataRow["RE_Fax_Number"]);
            }
            else
                this.PrimaryDataRow["Fax"] = DBNull.Value;
        }

        /// <summary>
        /// Saves the Contact record
        /// </summary>
        /// <returns>Returns true for successful save else false</returns>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        protected bool AddRecord()
        {
            bool addRecord = false;

            //DS:27032013 - Set the fields which was earlier getting set on form formula.
            SetMobilePhoneFax();

            if (ContactDupCheck())
                addRecord=  false;
            else
            {                
                addRecord = base.SaveRecord();
                
                //Create a new row in the RE_Membership_History table.
                DataRow reMembershipHistoryRow = this.DataSet.Tables["RE_Membership_History_Contact_"].NewRow();
                reMembershipHistoryRow["Contact_Id"] = TypeConvert.ToDBValue(this.RecordId);
                reMembershipHistoryRow["Activity"] = "Enrolled";
                reMembershipHistoryRow["Activity_Description"] = "Member created.";
                reMembershipHistoryRow["Activity_Date"] = DateTime.Now;

                this.DataSet.Tables["RE_Membership_History_Contact_"].Rows.Add(reMembershipHistoryRow);

                addRecord = base.SaveRecord();
                base.LoadRecord();
            }
            return addRecord;
        }

        /// <summary>
        /// Check for duplicate Contacts. If found, then show the list and let the user modify the contact. Do not allow the user to create a duplicate Contact.
        /// </summary>
        /// <returns></returns>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private bool ContactDupCheck()
        {
            bool dupFound = false;
            try
            {
                if (this.PrimaryDataRow["RE_Membership_ID"] != DBNull.Value)
                {
                    DataTable contactsForMembership = Globals.GetDataTable("RE_Members with with Brand Id? Membership ID? Contact Id Not?",
                                new object[] { this.PrimaryDataRow["RE_Brand_Id"], this.PrimaryDataRow["RE_Membership_ID"],  
                                (this.RecordId==null)?null:TypeConvert.ToDBValue(this.RecordId)}, new string[] { "Contact_Id" });

                    if (contactsForMembership != null && contactsForMembership.Rows.Count > 0)
                    {
                        ShowListAndEdit(contactsForMembership, "Membership ID.");
                        return true;
                    }
                }

                DataTable contactsForBrandAndEmail = Globals.GetDataTable("RE_Members with with Brand Id? Email? Contact Id Not?",
                    new object[] { this.PrimaryDataRow["RE_Brand_Id"], this.PrimaryDataRow["Email"], 
                        (this.RecordId==null)?null:TypeConvert.ToDBValue(this.RecordId) }, new string[] { "Contact_Id" });

                if (contactsForBrandAndEmail != null && contactsForBrandAndEmail.Rows.Count > 0)
                {
                    ShowListAndEdit(contactsForBrandAndEmail, "Email.");
                    dupFound = true;
                }
            }
            catch (Exception exc)
            {
                return Globals.HandleException(exc, true);
            }
            return dupFound;
        }

        /// <summary>
        /// Show the user duplicate contacts and allow him to modify.
        /// </summary>
        /// <param name="contacts">Duplicate Contacts</param>
        /// <param name="dupField">Duplicate Field</param>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-05-18      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowListAndEdit(DataTable contacts, string dupField)
        {
            PivotalMessageBox.Show("Duplicate Contacts found for the Field: " + dupField + Environment.NewLine + "Please examine the duplicates and Modify.", 
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            
            //Showing all duplicate records for user selection
            Id selectedDuplicateContactId = Globals.ShowSingleSelectionList(contacts, "Duplicate Contacts", string.Empty);
            if (selectedDuplicateContactId != null)
                Globals.ShowModalForm("Contact", selectedDuplicateContactId, null);
        }
    }
}
